<?php
/**
 * 投票
 */

namespace app\vote\controller;


use app\vote\model\Vote;
use app\vote\model\VoteUserLink;
use think\Controller;
use think\Request;

class Index extends Controller
{

    protected function getUserId(){
        return 11;
    }

    public function index(){
        $voteModel = new Vote();
        $this->assign('_voteList',$voteModel->getVoteList());
        return $this->fetch('');
    }

    public function addVote(){
        return $this->fetch('add_vote');
    }

    public function doAddVote(){
        $request = Request::instance();
        $title = $request->post('title');
        $optionTitleArray = $request->post('option_title/a');

        $voteModel = new Vote();

        $optionList = array();
        foreach ($optionTitleArray as $title){
            $optionList[] = array('option_title' => $title);
        }
        $res = $voteModel->addVote($title,$optionList);
        if(empty($res)){
            $this->error('失败');
        }else{
            $this->success('成功','/vote/Index/index');
        }
    }

    public function vote(){
        $request = Request::instance();
        $voteId = $request->param('id');

        $voteModel = new Vote();
        $voteInfo = $voteModel->getInfo($voteId);

        $voteUserLinkModel = new VoteUserLink();
        $linkInfo = $voteUserLinkModel->getLinkInfo($this->getUserId(),$voteId);

        $this->assign('_voteInfo', $voteInfo);
        $this->assign('_linkInfo', $linkInfo);
        return $this->fetch('vote');
    }

    public function doVote(){
        $request = Request::instance();
        $voteId = $request->post('vote_id');
        $voteOptionIdList = $request->post('vote_option_id/a');
        $voteUserLinkModel = new VoteUserLink();
        if(!$voteUserLinkModel->addLink($this->getUserId(),$voteId,$voteOptionIdList)){
            $this->error('已经参与投票');
        }else{
            $this->success('成功','/vote/Index/index');
        }
    }


}